/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.biz.service;

import java.io.File;
import java.lang.reflect.Method;
import java.util.*;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.*;
import com.thinkgem.jeesite.modules.biz.dao.*;
import com.thinkgem.jeesite.modules.biz.entity.*;
import com.thinkgem.jeesite.modules.biz.form.BizOrderForm;
import com.thinkgem.jeesite.modules.biz.form.BizOrderdetailForm;
import com.thinkgem.jeesite.modules.biz.vo.BizGoodsVO;
import com.thinkgem.jeesite.modules.biz.vo.ResultVO;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.AutoNameUtils;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.sys.utils.ResultVOUtil;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;

/**
 * 商品的ControllerService
 * @author tiancheng
 * @version 2018-07-12
 */
@Service
@Transactional(readOnly = true)
public class BizGoodsService extends CrudService<BizGoodsDao, BizGoods> {

	@Autowired
	private BizGoodsDao bizGoodsDao;
	@Autowired
	private BizGoodsCategoryDao bizGoodsCategoryDao;
	@Autowired
	private BizOrderDao bizOrderDao;
	@Autowired
	private BizOrderdetailDao bizOrderdetailDao;
	@Autowired
	private BizGoodsClassifyDao bizGoodsClassifyDao;
	@Autowired
	private BizSupplierDao bizSupplierDao;
	@Autowired
	private BizStorageDao bizStorageDao;


	public BizGoodsVO getApi(String id) {
		return bizGoodsDao.getApi(id);
	}

	public BizGoods get(String id) {
		return super.get(id);
	}

	public Integer getStockAmountByGoodsCode(String bizGoodsCode) {
		return bizGoodsDao.getStockAmountByGoodsCode(bizGoodsCode);
	}

	
	public List<BizGoods> findList(BizGoods bizGoods) {
		return super.findList(bizGoods);
	}

	public List<BizGoodsVO> findListForApi(BizGoods bizGoods) {
		return bizGoodsDao.findListForApi(bizGoods);
	}

	public List<BizGoodsVO> findAllListForApi(int pageNo,int pageSize,String classifyId,String searchKey) {
		int startIndex = (pageNo-1) * pageSize;
		return bizGoodsDao.findAllListForApi(startIndex,pageSize,classifyId,searchKey);
	}

	public List<BizGoods> findAllWarningGoodsList(BizGoods bizGoods) {
		return bizGoodsDao.findAllWarningGoodsList(bizGoods);
	}
	
	public Page<BizGoods> findPage(Page<BizGoods> page, BizGoods bizGoods) {
		return super.findPage(page, bizGoods);
	}
	
	@Transactional(readOnly = false)
	public void save(BizGoods bizGoods) {
		if(null == bizGoods.getGoodsId() || bizGoods.getGoodsId().equals("")){
			bizGoods.setGoodsId(IdGen.uuid());
			Integer stockAmount = bizGoods.getStockAmount();
			String purchasingAmount = bizGoods.getPurchasingAmount();
			if (stockAmount == null){
				bizGoods.setStockAmount(0);
			}
			if(StringUtils.isEmpty(purchasingAmount)){
				bizGoods.setPurchasingAmount("0");
			}
		}

		String supplierId = bizGoods.getSupplierId();
		Integer storageId = bizGoods.getStorageId();

		if (supplierId != null){
			BizSupplier bizSupplier = bizSupplierDao.get(supplierId.toString());
			if (bizSupplier != null){
				bizGoods.setSupplierName(bizSupplier.getSupplierName());
			}
		}
		if (storageId != null){
			BizStorage bizStorage = bizStorageDao.get(storageId.toString());
			if (bizStorage != null){
				bizGoods.setStorageName(bizStorage.getStorageName());
			}
		}
		super.save(bizGoods);
	}

	@Transactional(readOnly = false)
	public void update(BizGoods bizGoods) {
		User user = UserUtils.getUser();
		if (StringUtils.isNotBlank(user.getId())){
			bizGoods.setUpdateBy(user);
		}
		bizGoods.setUpdateDate(new Date());
		bizGoodsDao.update(bizGoods);
	}
	
	@Transactional(readOnly = false)
	public void delete(BizGoods bizGoods) {
		super.delete(bizGoods);
	}


	@Transactional(readOnly = false)
	public void updateDayNum(BizGoods bizGoods){
		bizGoodsDao.updateDayNum(bizGoods);
	}


	@Transactional(readOnly = false)
	public void updateDayNum0(){
		bizGoodsDao.updateDayNum0();
	}

	 /**
	  * 根据集合查询商品
	  * @author tiancheng
	  * @date 2018/7/13 11:23
	  * @param ids
	  * @return
	  */
	public List<BizGoods> selectGoodsListByIds(List<String> ids){
		return dao.selectGoodsListByIds(ids);
	}


	 /**
	  * 修改库存和采购数
	  * @author tiancheng
	  * @date 2018/7/14 11:55
	  * @param bizGoods
	  * @return
	  */
	@Transactional(readOnly = false)
	public void updateInfo(BizGoods bizGoods) {
		dao.updateInfo(bizGoods);
	}

	/**
	 * 将map转换为实体
	 * @param map
	 * @return
	 * xuchen
	 */
	public BizGoods mapToGoods(Map<String, String> map){
		StringBuffer errorMsg = new StringBuffer();
		errorMsg.append("错误信息:");
		boolean isCanSave = true;//是否可以保存
		BizGoods goods = new BizGoods();
		//map信息写进实体类
		//将map里的值放到实体类里
		Set<String> keys = map.keySet();
		try{
			for (String key : keys) {
				String value = map.get(key);
				if (StringUtils.isNotEmpty(value)) {
					String setMethodName = "set" + key.substring(0, 1).toUpperCase() + key.substring(1);
					Method setMethod = goods.getClass().getMethod(setMethodName, String.class);
					setMethod.invoke(goods, value);
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}

		//编码校验
		String goodsCode = goods.getGoodsCode();
		if (StringUtils.isNotEmpty(goodsCode)) {
			//判断编码是否重复 true=重复
			boolean isRepeat = isGoodsCodeRepeat(goodsCode);
			if(!isRepeat){
				isCanSave = false;
				errorMsg.append("商品编码重复；");
			}
		}else{
			isCanSave = false;
			errorMsg.append("商品编码不可为空；");
		}
		//名称校验
		String goodsName = goods.getGoodsName();
		if(StringUtils.isEmpty(goodsName)){
			isCanSave = false;
			errorMsg.append("商品名称不可为空；");
		}

		//单位校验
		String unit = goods.getUnit();
		if (StringUtils.isEmpty(unit)){
			isCanSave = false;
			errorMsg.append("单位不可为空；");
		}

		//仓库校验
		String storageName = goods.getStorageName();
		if (StringUtils.isEmpty(storageName)){
			isCanSave = false;
			errorMsg.append("仓库名称不能为空；");
		}else{
			BizStorage bizStorage = bizStorageDao.findByName(storageName);
			if(bizStorage != null && bizStorage.getStorageId() != null){
				goods.setStorageId(bizStorage.getStorageId());
			}else{
				isCanSave = false;
				errorMsg.append("未找到该仓库:"+goods.getSupplierName()+";");
			}
		}

		//最小请购数校验
		String minPurchaseQuantity = goods.getMinPurchaseQuantityStr();
		if (StringUtils.isEmpty(minPurchaseQuantity)){
			isCanSave = false;
			errorMsg.append("最小请购数不可为空；");
		}else{
			for (int i = minPurchaseQuantity.length();--i>=0;){
				if (!Character.isDigit(minPurchaseQuantity.charAt(i))){
					isCanSave = false;
					errorMsg.append("最小请购数应该为整数；");
					break;
				}
			}
		}

		//填充项目
		String goodsCategoryName = goods.getGoodsCategoryName();
		if(StringUtils.isNotEmpty(goodsCategoryName)){
			String[] categoryNames = goodsCategoryName.split(";");
			if(categoryNames != null && categoryNames.length > 0){
				for (String categoryName : categoryNames) {
					BizGoodsCategory bizGoodsCategory = bizGoodsCategoryDao.getByName(categoryName);
					if(bizGoodsCategory != null && StringUtils.isNotEmpty(bizGoodsCategory.getId())){
						goods.setGoodsCategoryId(bizGoodsCategory.getId());
					}else{
						isCanSave = false;
						errorMsg.append("项目名称不规范或填写错误:"+categoryName+"；");
						break;
					}
				}
			}
		}
		//商品分类
		String classifyName = goods.getClassifyName();
		if(StringUtils.isNotEmpty(classifyName)){
			//String bizGoodsClassify = DictUtils.getDictValue(goods.getClassifyName(), "biz_goods_classify", "");
			BizGoodsClassify bizGoodsClassifies = bizGoodsClassifyDao.findByName(classifyName);
			if(bizGoodsClassifies != null && StringUtils.isNotEmpty(bizGoodsClassifies.getId())){
				goods.setClassifyId(bizGoodsClassifies.getId());
			}else{
				isCanSave = false;
				errorMsg.append("商品分类填写错误:"+goods.getClassifyName()+"；");
			}
		}


		//供应商
		String supplierName = goods.getSupplierName();
		if (StringUtils.isEmpty(supplierName)){
			isCanSave = false;
			errorMsg.append("供应商不可为空；");
		}else{
			BizSupplier bizSupplier = bizSupplierDao.findByName(supplierName);
			if(bizSupplier != null && StringUtils.isNotEmpty(bizSupplier.getSupplierId())){
				goods.setSupplierId(bizSupplier.getSupplierId());
			}else{
				isCanSave = false;
				errorMsg.append("未找到该供应商:"+goods.getSupplierName()+";");
			}
		}

		//保质期整数校验
		String expirationDate = goods.getExpirationDate();
		if(StringUtils.isNotEmpty(expirationDate)){
			for (int i = expirationDate.length();--i>=0;){
				if (!Character.isDigit(expirationDate.charAt(i))){
					isCanSave = false;
					errorMsg.append("保质期应该为整数；");
					break;
				}
			}
		}
		goods.setIsCanSave(isCanSave);
		goods.setErrorMsg(errorMsg.toString());
		return goods;
	}



	 /**
	  * 导入时的添加商品
	  * @author tiancheng
	  * @date 2018/11/9 13:43
	  * @param
	  * @return
	  */
	@Transactional(readOnly = false)
	public Map<String,Object> importGoods(BizGoods bizGoods,StringBuilder failureMsg){
		Map<String,Object> re = new HashMap<>();
		//用于判断是否可以保存
		boolean isCanSave = true;
		//判断编号是否存在
		if(StringUtils.isEmpty(bizGoods.getGoodsCode())){
			isCanSave = false;
			failureMsg.append("<br/>商品编号 "+bizGoods.getGoodsCode()+" 不能为空; ");
		}
		//判断商品名称
		if(StringUtils.isEmpty(bizGoods.getGoodsName())){
			isCanSave = false;
			failureMsg.append("<br/>商品名称 "+bizGoods.getGoodsName()+" 不能为空; ");
		}
		//判断最小请购数
		if(StringUtils.isEmpty(bizGoods.getMinPurchaseQuantityStr())){
			isCanSave = false;
			failureMsg.append("<br/>最小请购数 "+bizGoods.getGoodsCode()+" 不能为空; ");
		}else{
			bizGoods.setMinPurchaseQuantity(Integer.valueOf(bizGoods.getMinPurchaseQuantityStr()));
		}
		//判断仓库
		if(!StringUtils.isEmpty(bizGoods.getStorageName())){
			BizStorage bizStorage = bizStorageDao.findByName(bizGoods.getStorageName());
			if(bizStorage != null && bizStorage.getStorageId() != null){
				bizGoods.setStorageId(bizStorage.getStorageId());
			}else{
				isCanSave = false;
				failureMsg.append("<br/>仓库 "+bizGoods.getStorageName()+" 不存在; ");
			}
		}else{
			isCanSave = false;
			failureMsg.append("<br/>仓库名称 "+bizGoods.getStorageName()+" 不能为空; ");
		}

		//判断项目
		String goodsCategoryName = bizGoods.getGoodsCategoryName();
		if(StringUtils.isNotEmpty(goodsCategoryName)){
			if(goodsCategoryName.indexOf(";") != -1){
				String[] categoryNames = goodsCategoryName.split(";");
				if(categoryNames != null && categoryNames.length > 0){
					for (String categoryName : categoryNames) {
						BizGoodsCategory bizGoodsCategory = bizGoodsCategoryDao.getByName(categoryName);
						if(bizGoodsCategory != null && StringUtils.isNotEmpty(bizGoodsCategory.getId())){
							bizGoods.setGoodsCategoryId(bizGoodsCategory.getId());
						}else{
							isCanSave = false;
							failureMsg.append("<br/>项目 "+bizGoods.getGoodsCategoryName()+" 不存在; ");
						}
					}
				}
			}else{
				BizGoodsCategory bizGoodsCategory = bizGoodsCategoryDao.getByName(goodsCategoryName);
				if(bizGoodsCategory != null && StringUtils.isNotEmpty(bizGoodsCategory.getId())){
					bizGoods.setGoodsCategoryId(bizGoodsCategory.getId());
				}else{
					isCanSave = false;
					failureMsg.append("<br/>项目 "+bizGoods.getGoodsCategoryName()+" 不存在; ");
				}
			}

		}

		//判断商品分类
		String classifyName = bizGoods.getClassifyName();
		if(StringUtils.isNotEmpty(classifyName)){
			BizGoodsClassify bizGoodsClassifies = bizGoodsClassifyDao.findByName(classifyName);
			if(bizGoodsClassifies != null && StringUtils.isNotEmpty(bizGoodsClassifies.getId())){
				bizGoods.setClassifyId(bizGoodsClassifies.getId());
			}else{
				isCanSave = false;
				failureMsg.append("<br/>商品分类 "+bizGoods.getSupplierName()+" 不存在; ");
			}
		}

		//判断供应商
		String supplierName = bizGoods.getSupplierName();
		if (StringUtils.isEmpty(supplierName)){
			isCanSave = false;
			failureMsg.append("<br/>供应商 "+bizGoods.getSupplierName()+" 不能为空; ");
		}else{
			BizSupplier bizSupplier = bizSupplierDao.findByName(supplierName);
			if(bizSupplier != null && StringUtils.isNotEmpty(bizSupplier.getSupplierId())){
				bizGoods.setSupplierId(bizSupplier.getSupplierId());
			}else{
				isCanSave = false;
				failureMsg.append("<br/>供应商 "+bizGoods.getSupplierName()+" 不存在; ");
			}
		}
		if(isCanSave){
			bizGoods.setGoodsId(IdGen.uuid());
			//默认库存为0
			bizGoods.setStockAmount(0);
			bizGoods.setSureStockAmount(0);
			bizGoods.setWaitStockAmount(0);
			bizGoods.setPurchasingAmount("0");
			super.save(bizGoods);
		}
		re.put("isCanSave",isCanSave);
		re.put("failureMsg",failureMsg);
		//返回的信息
		return re;
	}

	/**
	 * 判断商品编码是否重复
	 * @param bizGoodsCode
	 * @return
	 */
	public boolean isGoodsCodeRepeat(String bizGoodsCode){
		boolean flag = true;
		if(StringUtils.isNotEmpty(bizGoodsCode)){
			Integer count = bizGoodsDao.getCountGoodsCode(bizGoodsCode);
			if(count != null && count >= 1){
				flag = false;
			}
		}
		return flag;
	}


	 /**
	  * 新的CRM下单后修改可用库存和代发货数（拆分订单）
	  * @author tiancheng
	  * @date 2018/11/29 11:44
	  * @param
	  * @return
	  */
	@Transactional(readOnly = false)
	public ResultVO updateInfoNew(BizOrderForm bizOrderForm){
		//订单的拆单
		List<BizOrderdetailForm> coldChainOrderDetailList = new ArrayList<>();  // 冷链
	 	List<BizOrderdetailForm> equipmentOrderDetailList = new ArrayList<>(); // 设备
	 	List<BizOrderdetailForm> cashRegisterOrderDetailList = new ArrayList<>(); //收音机
	 	List<BizOrderdetailForm> productOrderDetailList = new ArrayList<>(); // 酱料
		List<BizOrderdetailForm> weiWoOrderDetailList = new ArrayList<>(); // 微沃

		for (BizOrderdetailForm bizOrderdetailForm:bizOrderForm.getSmOrderdetailList()) {
			if(null != bizOrderdetailForm.getCode() && bizOrderdetailForm.getCode().startsWith("L")){
				coldChainOrderDetailList.add(bizOrderdetailForm);
			}else if(null != bizOrderdetailForm.getCode() && bizOrderdetailForm.getCode().startsWith("J")){
				productOrderDetailList.add(bizOrderdetailForm);
			}else if(null != bizOrderdetailForm.getCode() && bizOrderdetailForm.getCode().startsWith("K")){
				cashRegisterOrderDetailList.add(bizOrderdetailForm);
			}else if(null != bizOrderdetailForm.getCode() && bizOrderdetailForm.getCode().startsWith("B")){
				equipmentOrderDetailList.add(bizOrderdetailForm);
			}else if(null != bizOrderdetailForm.getCode() && bizOrderdetailForm.getCode().startsWith("W")){
				weiWoOrderDetailList.add(bizOrderdetailForm);
			}
		}
		//继续拆分可出库和不可出库的订单
		demolitionOrder(bizOrderForm,coldChainOrderDetailList,"L");
		demolitionOrder(bizOrderForm,productOrderDetailList,"J");
		demolitionOrder(bizOrderForm,cashRegisterOrderDetailList,"K");
		demolitionOrder(bizOrderForm,equipmentOrderDetailList,"B");
		demolitionOrder(bizOrderForm,weiWoOrderDetailList,"W");
		return ResultVOUtil.success();
	}


	 /**
	  * 订单拆分为可出库和不可出库的订单
	  * @author tiancheng
	  * @date 2018/11/29 11:04
	  * @param list 要拆分的订单
	  * @param type L，冷链  J，酱料  B，设备  K，收银机  W，微沃
	  * @return
	  */
	public void demolitionOrder(BizOrderForm bizOrderForm,List<BizOrderdetailForm> list,String type){
		List<BizOrderdetail> listK = new ArrayList<>();  // 可出库的订单明细
		List<BizOrderdetail> listB = new ArrayList<>();  // 不可出库的订单明细
		if(null != list && list.size() > 0){
			//添加订单的基本信息
			BizOrder bizOrder = new BizOrder();	//可出库订单
			bizOrder.setOrderType("0"); //出库类别为正常出库
			bizOrder.setOrderStatus("0");//订单的状态 待出库
			bizOrder.setPushDate(new Date()); //由CRM推送来的时间
			//设置订单属性
			BeanUtils.copyProperties(bizOrderForm,bizOrder);
			//设置创建人和更新人
			User createBy = new User();
			createBy.setId(bizOrderForm.getCreateBy());
			createBy.setName(bizOrderForm.getCreateByName());
			bizOrder.setCreateBy(createBy);
			bizOrder.setCreateByName(bizOrderForm.getCreateByName());
			User updateBy = new User();
			updateBy.setId(bizOrderForm.getCreateBy());
			updateBy.setName(bizOrderForm.getCreateByName());
			bizOrder.setUpdateBy(updateBy);
			if(type.equals("K")){
				bizOrder.setOrderGenre("50");
			}else if(type.equals("J")){
				bizOrder.setOrderGenre("20");
			}else if(type.equals("B")){
				bizOrder.setOrderGenre("30");
			}else if(type.equals("L")){
				bizOrder.setOrderGenre("40");
			}else if(type.equals("W")){
				bizOrder.setOrderGenre("60");
			}
			//待审核状态
			bizOrder.setOrderApprovalStatus("20");

			//拆分可出库的订单和不可出库的订单
			for (BizOrderdetailForm orderDetail:list) {
				BizGoods bizGoods = new BizGoods();
				bizGoods.setGoodsCode(orderDetail.getCode());
				List<BizGoods> bizGoodsList = bizGoodsDao.findList(bizGoods);
				bizGoods = bizGoodsList.get(0);
				//获取仓库的可用库存数和代发货数
				Integer sureStockAmount = bizGoods.getSureStockAmount();
				Integer waitStockAmount = bizGoods.getWaitStockAmount();
				Integer quantity = orderDetail.getQuantity(); //本次的出库数
				//判断该商品能不能出库
				if(quantity > sureStockAmount){
					//不可出库
					BizOrderdetail bizOrderdetail = new BizOrderdetail();
					BeanUtils.copyProperties(orderDetail,bizOrderdetail);

					bizOrderdetail.setSurplusQuantity(bizOrderdetail.getQuantity()); // 设置剩余出库数
					bizOrderdetail.setSpecification(orderDetail.getSpecifications());	//设置规格
					bizOrderdetail.setIsDeliver("1");	//不可出库
					bizOrderdetail.setProjectdetailId(bizGoods.getGoodsId());	//正确商品id

					// 添加创建人  更新人
					User user = new User();
					user.setId(orderDetail.getCreateBy());
					user.setName(orderDetail.getCreateByName());
					bizOrderdetail.setCreateBy(user);
					user.setId(orderDetail.getUpdateBy());
					user.setName(orderDetail.getUpdateByName());
					bizOrderdetail.setUpdateBy(user);
					listB.add(bizOrderdetail);
				}else{
					//可出库
					BizOrderdetail bizOrderdetail = new BizOrderdetail();
					BeanUtils.copyProperties(orderDetail,bizOrderdetail);
					bizOrderdetail.setIsDeliver("0");	//可出库
					bizOrderdetail.setProjectdetailId(bizGoods.getGoodsId());	//正确商品id
					bizOrderdetail.setSurplusQuantity(bizOrderdetail.getQuantity()); // 设置剩余出库数
					bizOrderdetail.setSpecification(orderDetail.getSpecifications());	//设置规格

					// 添加创建人  更新人
					User user = new User();
					user.setId(orderDetail.getCreateBy());
					user.setName(orderDetail.getCreateByName());
					bizOrderdetail.setCreateBy(user);
					user.setId(orderDetail.getUpdateBy());
					user.setName(orderDetail.getUpdateByName());
					bizOrderdetail.setUpdateBy(user);
					listK.add(bizOrderdetail);

					//修改可用库存数和代发货数
					bizGoods.setSureStockAmount(sureStockAmount - quantity);
					bizGoods.setWaitStockAmount(waitStockAmount + quantity);
					//刷新库存信息
					bizGoodsDao.updateInfo(bizGoods);
				}

			}
			//添加可出库的订单
			if(null != listK && listK.size() > 0){
				String orderId = IdGen.uuid();
				bizOrder.setId(orderId);
				bizOrder.setIsCanOut("1");
				//生成条码
				String name = bizOrderForm.getName()+type+"K";
				bizOrder.setName(name);
				//生成条形码的地址
				String txmPath = exportDir()+name+".jpg";
				BarcodeUtil.createBarcode(name, txmPath);
				//修改出库单的条码路径
				if(txmPath.indexOf("userfiles") != -1){
					String[] paths = txmPath.split("userfiles");
					bizOrder.setTmUrl("/userfiles"+paths[1]);
				}
				bizOrderDao.insert(bizOrder);
				for (BizOrderdetail bizOrderdetail:listK) {
					bizOrderdetail.setId(IdGen.uuid());
					bizOrderdetail.setOutboundOrderPid(orderId);
					//添加订单明细
					bizOrderdetailDao.insert(bizOrderdetail);
				}

			}
			//添加不可出库的订单
			if(null != listB && listB.size() > 0){
				String orderId = IdGen.uuid();
				bizOrder.setId(orderId);
				bizOrder.setIsCanOut("0");
				//生成条码
				String name = bizOrderForm.getName()+type+"B";
				bizOrder.setName(name);
				//生成条形码的地址
				String txmPath = exportDir()+name+".jpg";
				BarcodeUtil.createBarcode(name, txmPath);
				//修改出库单的条码路径
				if(txmPath.indexOf("userfiles") != -1){
					String[] paths = txmPath.split("userfiles");
					bizOrder.setTmUrl("/userfiles"+paths[1]);
				}
				bizOrderDao.insert(bizOrder);
				for (BizOrderdetail bizOrderdetail:listB) {
					bizOrderdetail.setId(IdGen.uuid());
					bizOrderdetail.setOutboundOrderPid(orderId);
					//添加订单明细
					bizOrderdetailDao.insert(bizOrderdetail);
				}
			}
		}
	}

	 /**
	  * CRM下单后修改可用库存和代发货数
	  * @author tiancheng  
	  * @date 2018/10/4 14:57
	  * @param
	  * @return   
	  */
	 @Transactional(readOnly = false)
	 public ResultVO updateInfo(BizOrderForm bizOrderForm){
		if(null != bizOrderForm && null != bizOrderForm.getSmOrderdetailList() && StringUtils.isNotEmpty(bizOrderForm.getId())){
			//获取该出库单是否已经存在
			BizOrder bizOrder = bizOrderDao.get(bizOrderForm.getId());
			//不可出库单
			BizOrder bizOrderF = bizOrderDao.get(bizOrderForm.getId()+"F");

			if(bizOrder != null){
				//已经存在了，可用库存重新计算
				BizOrderdetail bizOrderdetail = new BizOrderdetail();
				bizOrderdetail.setOutboundOrderPid(bizOrderForm.getId());
				//ERP中已经存在的订单
				List<BizOrderdetail> bizOrderdetailList = bizOrderdetailDao.findList(bizOrderdetail);
				if(null != bizOrderdetailList) {
					//将旧订单的库存还原
					for (BizOrderdetail orderdetail : bizOrderdetailList) {
						BizGoods bizGoods = new BizGoods();
						bizGoods.setGoodsCode(orderdetail.getCode());
						List<BizGoods> bizGoodsList = bizGoodsDao.findList(bizGoods);
						bizGoods = bizGoodsList.get(0);
						//修改可用库存数和代发货数
						Integer sureStockAmount = bizGoods.getSureStockAmount();
						Integer waitStockAmount = bizGoods.getWaitStockAmount();
						Integer quantity = orderdetail.getQuantity();

						bizGoods.setSureStockAmount(sureStockAmount + quantity);
						bizGoods.setWaitStockAmount(waitStockAmount - quantity);
						//刷新库存信息
						bizGoodsDao.updateInfo(bizGoods);
					}
				}
				//删除订单明细
				bizOrderdetailDao.deleteByOrderId(bizOrder.getId());
				//删除订单
				bizOrderDao.realDelete(bizOrder);
			}


			if(bizOrderF != null){
				//删除不可出库订单明细
				bizOrderdetailDao.deleteByOrderId(bizOrderF.getId());
				//删除不可出库订单
				bizOrderDao.realDelete(bizOrderF);
			}


			//获取订单的明细
			List<BizOrderdetailForm> bizOrderdetailFormList = bizOrderForm.getSmOrderdetailList();

			ArrayList<BizOrderdetailForm> canOutOrderDetails = new ArrayList<>();	//可以发货的明细List
			ArrayList<BizOrderdetailForm> cannotOutOrderDetails = new ArrayList<>();	//不可以发货的明细List

			if(bizOrderdetailFormList != null && bizOrderdetailFormList.size() > 0){
				for (BizOrderdetailForm bizOrderdetailForm : bizOrderdetailFormList) {
					//判断订单是否可以出库或者是可以部分可出库
					if("0".equals(bizOrderdetailForm.getIsDeliver())){
						//可以发货的明细
						canOutOrderDetails.add(bizOrderdetailForm);
					}
					if("1".equals(bizOrderdetailForm.getIsDeliver())){
						//不可以发货的明细
						cannotOutOrderDetails.add(bizOrderdetailForm);
					}
				}
			}


			//创建可出库订单
			if(canOutOrderDetails != null && canOutOrderDetails.size() > 0){
				bizOrder = new BizOrder();	//可出库订单
				bizOrder.setOrderType("0"); //出库类别为正常出库
				bizOrder.setOrderStatus("0");//订单的状态 待出库
				bizOrder.setIsCanOut("1");	//可以出库
				//设置订单属性
				BeanUtils.copyProperties(bizOrderForm,bizOrder);
				//设置创建人和更新人
				User createBy = new User();
				createBy.setId(bizOrderForm.getCreateBy());
				createBy.setName(bizOrderForm.getCreateByName());
				bizOrder.setCreateBy(createBy);
				bizOrder.setCreateByName(bizOrderForm.getCreateByName());
				User updateBy = new User();
				updateBy.setId(bizOrderForm.getCreateBy());
				updateBy.setName(bizOrderForm.getCreateByName());
				bizOrder.setUpdateBy(updateBy);
				//待审核状态
				bizOrder.setOrderApprovalStatus("10");
				//生成条码
				String name = bizOrder.getName();
				//生成条形码的地址
				String txmPath = exportDir()+name+"CKD.jpg";
				BarcodeUtil.createBarcode(name, txmPath);
				//修改出库单的条码路径
				if(txmPath.indexOf("userfiles") != -1){
					String[] paths = txmPath.split("userfiles");
					bizOrder.setTmUrl("/userfiles"+paths[1]);
				}
				bizOrderDao.insert(bizOrder);

				//循环订单明细修改库存
				for (BizOrderdetailForm bizOrderdetailForm:canOutOrderDetails) {
					BizGoods bizGoods = new BizGoods();
					bizGoods.setGoodsCode(bizOrderdetailForm.getCode());
					List<BizGoods> bizGoodsList = bizGoodsDao.findList(bizGoods);
					if(bizGoodsList != null && bizGoodsList.size() > 0){
						bizGoods = bizGoodsList.get(0);
						//修改可用库存数和代发货数
						Integer sureStockAmount = 0;
						//判断当前可用库存数是否大于本次出库数
						if(bizGoods.getSureStockAmount() >= bizOrderdetailForm.getQuantity()){
							sureStockAmount = bizGoods.getSureStockAmount() - bizOrderdetailForm.getQuantity();
						}
						Integer waitStockAmount = bizGoods.getWaitStockAmount() + bizOrderdetailForm.getQuantity();
						bizGoods.setSureStockAmount(sureStockAmount);
						bizGoods.setWaitStockAmount(waitStockAmount);
						bizGoodsDao.updateInfo(bizGoods);
					}
					//添加订单明细
					BizOrderdetail bizOrderdetail = new BizOrderdetail();
					BeanUtils.copyProperties(bizOrderdetailForm,bizOrderdetail);
					//查询ERP中的商品的id
					BizGoods goods = bizGoodsDao.getByGoodsCode(bizOrderdetailForm.getCode());
					//是否需要
					if(null != goods){
						if(null != bizOrderdetailForm.getProjectdetailId()){
							bizOrderdetail.setProjectdetailId(goods.getGoodsId());
							bizOrderdetail.setProjectdetailName(goods.getGoodsName());
						}
					}
					bizOrderdetail.setSurplusQuantity(bizOrderdetail.getQuantity()); // 设置剩余出库数
					bizOrderdetail.setSpecification(bizOrderdetailForm.getSpecifications());	//设置规格

					// 添加创建人  更新人
					User user = new User();
					user.setId(bizOrderdetailForm.getCreateBy());
					user.setName(bizOrderdetailForm.getCreateByName());
					bizOrderdetail.setCreateBy(user);
					user.setId(bizOrderdetailForm.getUpdateBy());
					user.setName(bizOrderdetailForm.getUpdateByName());
					bizOrderdetail.setUpdateBy(user);
					bizOrderdetailDao.insert(bizOrderdetail);
				}

			}

			//创建不可出库订单
			if(cannotOutOrderDetails != null && cannotOutOrderDetails.size() > 0){
				bizOrderF = new BizOrder();	//不可出库订单
				bizOrderF.setOrderType("0"); //出库类别为正常出库
				bizOrderF.setOrderStatus("0");//订单的状态 待出库
				bizOrderF.setIsCanOut("0");	//不可以出库
				//设置订单属性
				BeanUtils.copyProperties(bizOrderForm,bizOrderF);
				//设置id 和 name  都带F
				bizOrderF.setId(bizOrderForm.getId() + "F");
				bizOrderF.setName(bizOrderForm.getName() + "F");
				//设置创建人和更新人
				User createBy = new User();
				createBy.setId(bizOrderForm.getCreateBy());
				createBy.setName(bizOrderForm.getCreateByName());
				bizOrderF.setCreateBy(createBy);
				bizOrderF.setCreateByName(bizOrderForm.getCreateByName());
				User updateBy = new User();
				updateBy.setId(bizOrderForm.getCreateBy());
				updateBy.setName(bizOrderForm.getCreateByName());
				bizOrderF.setUpdateBy(updateBy);
				//待审核状态
				bizOrderF.setOrderApprovalStatus("10");
				//生成条码
				String name = bizOrderF.getName();
				//生成条形码的地址
				String txmPath = exportDir()+name+"CKD.jpg";
				BarcodeUtil.createBarcode(name, txmPath);
				//修改出库单的条码路径
				if(txmPath.indexOf("userfiles") != -1){
					String[] paths = txmPath.split("userfiles");
					bizOrderF.setTmUrl("/userfiles"+paths[1]);
				}
				bizOrderDao.insert(bizOrderF);


				//创建不可出库单明细
				for (BizOrderdetailForm bizOrderdetailForm:cannotOutOrderDetails) {
					//添加订单明细
					BizOrderdetail bizOrderdetail = new BizOrderdetail();
					BeanUtils.copyProperties(bizOrderdetailForm,bizOrderdetail);
					bizOrderdetail.setOutboundOrderPid(bizOrderdetailForm.getOutboundOrderPid()+"F");
					//查询ERP中的商品的id
					BizGoods goods = bizGoodsDao.getByGoodsCode(bizOrderdetailForm.getCode());
					//是否需要
					if(null != goods){
						if(null != bizOrderdetailForm.getProjectdetailId()){
							bizOrderdetail.setProjectdetailId(goods.getGoodsId());
							bizOrderdetail.setProjectdetailName(goods.getGoodsName());
						}
					}
					bizOrderdetail.setSurplusQuantity(bizOrderdetail.getQuantity()); // 设置剩余出库数
					bizOrderdetail.setSpecification(bizOrderdetailForm.getSpecifications());	//设置规格

					// 添加创建人  更新人
					User user = new User();
					user.setId(bizOrderdetailForm.getCreateBy());
					user.setName(bizOrderdetailForm.getCreateByName());
					bizOrderdetail.setCreateBy(user);
					user.setId(bizOrderdetailForm.getUpdateBy());
					user.setName(bizOrderdetailForm.getUpdateByName());
					bizOrderdetail.setUpdateBy(user);
					bizOrderdetailDao.insert(bizOrderdetail);
				}
			}
		}
		return ResultVOUtil.success();
	}

	/**
	 * 通过商品编码查找商品
	 * @param goodsCode
	 * @return
	 */
	public BizGoods getByGoodsCode(String goodsCode) {
		return bizGoodsDao.getByGoodsCode(goodsCode);
	}
	@Transactional(readOnly = false)
	public void updateByGoodsCode(BizGoods bizGoods) {
		bizGoodsDao.updateByGoodsCode(bizGoods);
	}


	/**
	 * 通过商品编码查询商品数
	 * @param goodsCode
	 * @return
	 */
	public Integer findCountByGoodsCode(String goodsCode) {
		return bizGoodsDao.findCountByGoodsCode(goodsCode);
	}


	/**
	 * 生成条形码的路径
	 * @author tiancheng
	 * @date 2018/9/5 14:02
	 * @param
	 * @return
	 */
	public String exportDir(){
		//默认传到系统管理员的明下
		String exportDir =  FileUtils.path(Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + "1/files/exportFiles/" + DateUtils.getDate("yyyy-MM-dd") + "/");
		if (!new File(exportDir).exists()) {
			new File(exportDir).mkdirs();
		}
		return exportDir;
	}




}